/**
 * Copyright(c) 2013 Jade Techonologies Co., Ltd.
 *
 * History:
 *   13-7-2 下午2:42 Created by dwzhang
 */
package com.jade.framework.base.io;

import java.io.File;
import java.nio.charset.Charset;

import info.monitorenter.cpdetector.io.CodepageDetectorProxy;
import info.monitorenter.cpdetector.io.JChardetFacade;
import info.monitorenter.cpdetector.io.ParsingDetector;
import info.monitorenter.cpdetector.io.UnicodeDetector;

/**
 * 文件工具类。
 *
 * @author dwzhang
 * @version 1.0 13-7-2 下午2:42
 */
public class FileCharsetDetector
{
    static CodepageDetectorProxy detector = null;

    protected static CodepageDetectorProxy getDetectorProxy()
    {
        if (detector == null) {
            detector = CodepageDetectorProxy.getInstance();
            detector.add(new ParsingDetector(false));
//            detector.add(JChardetFacade.getInstance()); //编译不通过,暂时注释
            detector.add(UnicodeDetector.getInstance());
        }
        return detector;
    }

    public static String detectCharset(String path)
    {
        return detectCharset(new File(path));
    }

    public static String detectCharset(File file)
    {
        CodepageDetectorProxy detector = getDetectorProxy();
        java.nio.charset.Charset charset = null;
        try {
            charset = detector.detectCodepage(file.toURI().toURL());
        }
        catch (Throwable t) {
        }
        if (charset == null) {
            return Charset.defaultCharset().name();
        }
        else {
            return charset.name();
        }
    }
}
